package OrderService

import (
	"context"
	"gdshop-back-end-go/client-api/app/request/OrderReq"
	"gdshop-back-end-go/client-api/app/response/OrderResp"
	"gdshop-back-end-go/common/db"
	"gdshop-back-end-go/common/entity"
	"gdshop-back-end-go/common/response"
	"gdshop-back-end-go/service-member/AddressService"
	"gdshop-back-end-go/service-order/OrderService"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/os/gtime"
	"time"
)

// 用户关闭订单 判断状态，必须是 1待付款 才可以关闭订单
func Details(ctx context.Context, parames *OrderReq.Details) *response.JsonResponse {
	var oModel OrderResp.Details
	err := db.GetUnSafaTableAddDeleteWhere(ctx, "order").Where(
		"id = ? AND member_id = ?", parames.Id, parames.MemberId,
	).Struct(&oModel)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}

	oModel.StoreName = "自营"
	oModel.SubOrderList = OrderService.GetOrderSubByOrderId(ctx, oModel.Id)
	oModel.IsExpress = OrderService.OrderIsExpress(ctx, oModel.Id)
	oModel.IsShowPrimary = OrderService.OrderIsShowPrimary(oModel.Status)
	oModel.TipsList = OrderService.GetOrderTipsList(oModel.Id)
	countDownSecond := g.Cfg().GetInt64("queue.CloseNoPayOrder.delayTime") - (time.Now().Unix() - oModel.CreateAt)
	if countDownSecond < 1 {
		countDownSecond = 0
	}
	jieguo := g.Map{
		"order":              oModel,
		"addressInfo":        AddressService.GetMyAddressModel(ctx, oModel.AddressId, int(parames.MemberId)),
		"count_down_second":  countDownSecond,
		"photo_base_url":     g.Cfg().GetString("site.PhotoUrlProfix"),
		"next_status_text":   OrderService.GetNextStatusText(),
		"status_text":        OrderService.GetStatusText(),
		"refund_status_text": OrderService.GetRefundStatusText(),
	}
	// 更多信息
	moreInfo := g.Map{}
	moreInfo["time_line"] = getOrderInfoSteps(ctx, oModel.Id, oModel.CreateAt)
	moreInfo["dispatch_price"] = oModel.DispatchPrice
	moreInfo["coupon"] = getOrderCouponDiscount(ctx, oModel.Id)
	moreInfo["activity"] = getOrderActivityDiscount(ctx, oModel.Id)
	moreInfo["invoice"] = 0
	moreInfo["contact_customer"] = ""
	jieguo["more_info"] = moreInfo
	return response.SuccessByRequestMessageData(nil, "成功", jieguo)
}

func getOrderInfoSteps(ctx context.Context, orderId int, create_at int64) g.Map {
	resultMap := g.Map{
		"1": g.Map{
			"title":       "下单时间",
			"icon":        "el-icon-edit",
			"description": gtime.New(create_at).Format("Y-m-d H:i:s"),
		},
	}

	typeIn := []string{
		"back_pay",
		//"confirm_goods",
		"send_express",
		"confirm_order",
		"member_pay",
		"close_order",
	}
	var orderLogList []*entity.OrderLog
	err := db.GetUnSafaTable(ctx, "order_log").Where("order_id", orderId).Where("type IN (?)", typeIn).Fields(
		"id,order_id,type,admin_id,member_id,create_at",
	).Order("id ASC").Structs(&orderLogList)
	if err != nil {
		return resultMap
	}

	typeToInt := g.MapStrStr{
		"back_pay":      "2",
		"member_pay":    "2",
		"confirm_goods": "3",
		"send_express":  "4",
		"confirm_order": "5",
		"close_order":   "6",
	}

	olTypeTitles := g.MapStrStr{
		"back_pay":      "付款时间",
		"member_pay":    "付款时间",
		"confirm_goods": "备货时间",
		"send_express":  "发货时间",
		"confirm_order": "完成时间",
		"close_order":   "关闭时间",
	}
	olTypeIcons := g.MapStrStr{
		"back_pay":      "el-icon-money",
		"member_pay":    "el-icon-money",
		"confirm_goods": "el-icon-sell",
		"send_express":  "el-icon-truck",
		"confirm_order": "el-icon-s-claim",
		"close_order":   "el-icon-remove",
	}

	for _, item := range orderLogList {
		switch item.Type {
		case "back_pay", "member_pay", "send_express", "confirm_order", "close_order":
			resultMap[typeToInt[item.Type]] = g.Map{
				"title":       olTypeTitles[item.Type],
				"icon":        olTypeIcons[item.Type],
				"description": gtime.New(item.CreateAt).Format("Y-m-d H:i:s"),
			}
			break
		}
	}

	return resultMap
}

func getOrderCouponDiscount(ctx context.Context, orderId int) float64 {
	sum, err := db.GetUnSafaTableAddDeleteWhere(ctx, "order_sub_coupon").Where("order_id", orderId).Sum("discount")
	if err != nil {
		return 0
	}
	return sum
}

func getOrderActivityDiscount(ctx context.Context, orderId int) float64 {
	sum, err := db.GetUnSafaTableAddDeleteWhere(ctx, "order_sub_activity").Where("order_id", orderId).Sum("discount")
	if err != nil {
		return 0
	}
	return sum
}
